# -*- coding: utf-8 -*-
import os
import json
from io import BytesIO
from hashlib import md5

from flask import request, jsonify, send_from_directory
from PIL import Image

from . import app
from .database import (User,
                       Book,
                       Record,
                       db)
from .utils import get_isbn_info, allowed_file


@app.route("/book", methods=["GET"])
def get_books():
    page = request.args.get("page", 1)
    return jsonify({
        "status": True,
        "message": "ok",
        "data": [{
            "bid": book.bid,
            "title": book.title,
            "author": book.author,
            "price": book.price,
            "update_time": book.update_time.strftime(r"%Y-%m-%d"),
            "cover": book.cover
    } for book in (Book.select()
                       .where(Book.status == True)
                       .paginate(page, 10))]})


@app.route("/book", methods=["POST"])
def publish_book():
    try:
        data = json.loads(request.data)
    except ValueError:
        return jsonify({
            "status": False,
            "message": "参数不合法",
            "data": {}})
    
    if ("phone" not in data
        or "price" not in data
        or "images" not in data):
        return jsonify({
            "status": False,
            "message": "缺少参数",
            "data": {}})
    
    if "isbn" in data:
        isbn = data["isbn"]
        info = get_isbn_info(isbn)
        if (info["showapi_res_code"] == 0
            and info["showapi_res_body"]["remark"] == "success"):
            info = info["showapi_res_body"]["data"]
            info["isbn"] = isbn
        else:
            return jsonify({
                "status": False,
                "message": "ISBN信息查询失败",
                "data": info})
    else:
        try:
            info = {
                "title": data["title"],
                "author": data["author"]}
        except KeyError:
            return jsonify({
                "status": False,
                "message": "缺少参数",
                "data": {}})
    
    t = User.select().where(User.phone == data["phone"])
    if t:
        seller = t.get()
    else:
        seller = User.create(phone=data["phone"])
        seller.save()
    book = Book.create(title=info["title"],
                       author=info["author"],
                       seller=seller,
                       isbn=info.get("isbn"),
                       price=data["price"],
                       images=json.dumps(data["images"]),
                       cover=data["images"][0] if data["images"] else None)
    book.save()
    return jsonify({
        "status": True,
        "message": "ok",
        "data": {
            "bid": book.bid,
            "info": {
                "title": book.title,
                "seller": book.seller.phone,
                "price": book.price}}})


@app.route("/book/<int:bid>", methods=["GET"])
def get_book_info(bid):
    try:
        book = Book.get_by_id(bid)
    except Book.DoesNotExist:
        return jsonify({
            "status": False,
            "message": f"书本编号 {bid} 不存在",
            "data": {}})
    return jsonify({
        "status": True,
        "message": "ok",
        "data": {
            "title": book.title,
            "author": book.author,
            "seller": book.seller.phone,
            "isbn": book.isbn,
            "price": book.price,
            "update_time": book.update_time.strftime(r"%Y-%m-%d"),
            "images": json.loads(book.images)}})


@app.route("/book/<int:bid>", methods=["DELETE"])
def delete_book(bid):
    try:
        book = Book.get_by_id(bid)
    except Book.DoesNotExist:
        return jsonify({
            "status": False,
            "message": f"书本编号 {bid} 不存在",
            "data": {}})
    book.delete_instance()
    return jsonify({
        "status": True,
        "message": "ok",
        "data": {
            "bid": bid}})


@app.route("/image", methods=["POST"])
def upload_images():
    res = []
    if not request.files:
        return jsonify({
                "status": False,
                "message": "无上传文件",
                "data": {}})
    for name in request.files:
        file = request.files[name]
        if not allowed_file(file.filename):
            return jsonify({
                "status": False,
                "message": "文件格式不允许",
                "data": file.filename})
        tmp = BytesIO()
        file.save(tmp)
        tmp.seek(0)
        filename = f'{md5(tmp.read()).hexdigest()}.{file.filename.split(".")[-1]}'
        img = Image.open(tmp)
        width, height = img.size
        img.thumbnail((1000, height * (1000 / width)))
        path = os.path.join(app.config["UPLOAD_FOLDER"],
                            filename)
        img.save(path)
        res.append(filename)
    return jsonify({
        "status": True,
        "message": "ok",
        "data": res})


@app.route("/image/<filename>", methods=["GET"])
def get_images(filename):
    return send_from_directory(app.config["UPLOAD_FOLDER"],
                               filename)


@app.route("/book/<int:bid>/sell", methods=["POST"])
def sell_book(bid):
    try:
        data = json.loads(request.data)
    except ValueError:
        return jsonify({
            "status": False,
            "message": "参数不合法",
            "data": {}})

    try:
        book = Book.get_by_id(bid)
    except Book.DoesNotExist:
        return jsonify({
            "status": False,
            "message": f"书本编号 {bid} 不存在",
            "data": {}})

    if "phone" not in data:
        return jsonify({
            "status": False,
            "message": "缺少参数",
            "data": {}})
    
    t = User.select().where(User.phone == data["phone"])
    if t:
        buyer = t.get()
    else:
        buyer = User.create(phone=data["phone"])
        buyer.save()

    record = Record.create(user=buyer,
                        book=book,
                        type=1, # 1为卖出
                        price=book.price)
    record.save()

    Book.update(status=False).where(Book.bid == bid).execute()
    db.commit()

    return jsonify({
        "status": True,
        "message": "ok",
        "data": {
            "bid": book.bid,
            "title": book.title,
            "seller": book.seller.phone,
            "buyer": buyer.phone,
            "price": book.price
        }
    })
